import './dlg.css';

export class Dialog extends HTMLElement{
  constructor(dlgName){
    super();
    this.#init();
    this.#dlgName = dlgName;
    this.#$btnClose.onclick = this.#onClose.bind(this) 
    this.#$titlebar.onmousedown = (e)=>{
      this.#isDragging = true;
      this.#startX = e.pageX;
      this.#startY = e.pageY;
      this.#dlgX = this.#$dlg.offsetLeft;
      this.#dlgY = this.#$dlg.offsetTop;
    }
    document.body.addEventListener('mousemove', (e) =>{
      if(!this.#isDragging) return; 
      const offsetX = e.pageX-this.#startX,
            offsetY = e.pageY-this.#startY;
      console.log(offsetX, offsetY);
      this.#$dlg.style.left = (this.#dlgX +offsetX) + 'px';
      this.#$dlg.style.top = (this.#dlgY+ offsetY) + 'px';
    });
    document.body.addEventListener('mouseup',() =>{
      this.#isDragging = false;
    });
}
decorate(html, title){
  this.#$title.innerText = title;
  this.#$dlgMain.innerHTML = html;
}
  #init(){
    this.innerHTML = this.#html;
    this.$ = this.querySelector;
    this.#$btnClose = this.$('.close')
    this.#$titlebar = this.$('.titlebar')
    this.#$dlgMain = this.$('.main');
    this.#$dlg = this.$('.dialog')
    this.#$title = this.$('.title');
    this.#restore();
  }
#onClose(){
  localStorage[this.#dlgName + '-top'] = this.#$dlg.offsetTop;
  localStorage[this.#dlgName + '-left'] = this.#$dlg.offsetLeft;
  this.remove();
}
#restore(){
  console.log("#restore")
  console.log(this.#dlgName)
  this.#$dlg.style.top = (localStorage[this.#dlgName + '-top'] || 100) + 'px';
  this.#$dlg.style.left = (localStorage[this.#dlgName + '-left'] || 100) + 'px';
  console.log(localStorage.getItem(this.#dlgName+'-top'))
  console.log(localStorage.getItem(this.#dlgName+'-left'))
}
  #$btnClose = null;
  #$titlebar = null;
  #$title = null
  #$dlg = null;
  #$dlgMain = null;
  #isDragging = false;
  #startX = 0;
  #startY = 0;
  #dlgX = 0;
  #dlgY = 0;
  #dlgName = "";
#html = ''
  +'<div class="mask">'
    +'<div class="dialog">'
      +'<div class="titlebar">'
        +'<span class="title"></span> '
        +'<span class="close" title="关闭">✖</span>'
      +'</div>'
      +'<div class="main">'
      +'</div>'
    +'</div>'
  +'</div>';
}

